/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.manager;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.lvyh.lightframe.job.admin.bean.JobAlarmLogBean;
import com.lvyh.lightframe.job.admin.service.JobMainDataService;
import com.lvyh.lightframe.job.admin.util.ByteUtils;
import com.lvyh.lightframe.job.enums.AlarmType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@Service
public class TaskNodeManager {

    private final static Logger logger = LoggerFactory.getLogger(TaskNodeManager.class);

    public static final String TASK_PATH = "/tasks";

    public static final String TASK_PREFIX = "task-id-";

    @Autowired
    private ZkManager zkManager;

    @Autowired
    private JobMainDataService jobMainDataService;

    /**
     * Queue of nodes waiting to be deleted
     */
    private static BlockingQueue<Integer> readyToDelNodes = new LinkedBlockingQueue<>();

    @PreDestroy
    public void destroy() {
    }

    public void deleteNode() {
        Integer taskId = null;
        try {
            taskId = readyToDelNodes.take();
            String nodePath = zkManager.buildPath(TASK_PATH, TASK_PREFIX + taskId);
            zkManager.deleteNode(nodePath);
        } catch (Exception e) {
            if (taskId != null) {
                logger.warn("delete zk taskNode failed. taskId:{}", taskId);
                scheduleDelete(taskId);
            }
        }
    }

    public void scheduleDelete(Integer taskId) {

        if (taskId == null) {
            throw new RuntimeException("taskId can't be null");
        }

        if (!readyToDelNodes.offer(taskId)) {
            logger.error("put undeleted nodePath into toBeDeleted queue failed. taskId:{}", taskId);
            try {
                JobAlarmLogBean alarmLog = new JobAlarmLogBean();
                alarmLog.setAlarmTime(new Date());
                alarmLog.setAlarmType(AlarmType.ZK_TASK_NODE_DELETE_QUEUE_FULL.getKey());
                alarmLog.setAlarmName(AlarmType.ZK_TASK_NODE_DELETE_QUEUE_FULL.getValue());
                alarmLog.setAlarmDetail(AlarmType.ZK_TASK_NODE_DELETE_QUEUE_FULL.getDesc() + ",taskId:" + taskId);
                jobMainDataService.saveJobAlarmLog(alarmLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Create a task node and set task information
     *
     * @param taskId
     * @return True will be returned if the node is created successfully. False will be returned if the node already exists
     */
    public boolean createTaskNode(Integer taskId, Map<String, String> data) throws InterruptedException {
        if (taskId == null) {
            throw new RuntimeException("taskId can't be null");
        }
        String taskNode = zkManager.buildPath(TASK_PATH, TASK_PREFIX + taskId);
        int retry = 3;
        Exception exception = null;
        while (retry > 0) {
            retry--;
            try {
                return zkManager.createEphemeralNode(taskNode, getTaskNodeData(data));
            } catch (Exception e) {
                exception = e;
                TimeUnit.MILLISECONDS.sleep(500);
            }
        }

        throw new RuntimeException(exception);

    }

    private byte[] getTaskNodeData(Map<String, String> data) {
        Map<String, String> nodeData = Maps.newHashMap();
        nodeData.putAll(data);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        nodeData.put("_ctime_", sdf.format(new Date()));

        return ByteUtils.toBytes(JSON.toJSONString(nodeData));
    }

    /**
     * Delete node
     *
     * @param taskId
     * @throws Exception
     */
    public void removeTaskNode(Integer taskId) throws Exception {
        if (taskId == null) {
            throw new RuntimeException("taskId can't be null");
        }
        String taskNode = zkManager.buildPath(TASK_PATH, TASK_PREFIX + taskId);
        int retry = 3;
        Exception exception = null;
        boolean flag = true;
        while (retry > 0 && flag) {
            retry--;
            try {
                zkManager.deleteNode(taskNode);
                flag = false;
                return;
            } catch (Exception e) {
                exception = e;
                TimeUnit.MILLISECONDS.sleep(500);
            }
        }

        throw new RuntimeException(exception);
    }
}
